<template>
	<div class="limited">
		<el-row>
			<el-col :span="6">
				<div class="left-box">
					<div class="store-header flex_between">
						<div class="flex_between flex1">
							<div class="bold font_size16">成员管理</div>
						</div>
						<div class="iconBox">
							<text class="icon-font search-icon" @click="addOrEdt">&#xe606;</text>
						</div>
					</div>
					<LeftList ref="leftListRef" :templates="templates" :listData="listData"
						:selectedIndex.sync="selectedIndex" :lLoading="lLoading" :lNoMore="lNoMore" @loadFun="loadFun"
						@clickItem="clickItem">
						<div slot-scope="{row}" slot="name" class="">
							<div class="flex_between" style="align-items: flex-start;">
								<div class="img-box">
									<el-image class="img" :src="row.avatar"></el-image>
								</div>
								<div class="flex1 flex_between">
									<div class="">
										<div class="font_size16 bold"> {{ row.name }} </div>
										<div>
											<span class="font_black7 ellipsis2" :title="row.cellphone">{{ row.cellphone
												|| '' }}</span>
										</div>
									</div>
									<div class="flex_center_column">
										<div class="font_size14 font_green">{{ row.positionname }}</div>
										<div>
											<el-tag size="mini" :type="row.status == 1 ? '' : 'info'">{{ row.status == 1
												?
												'启用' : '未启用'
											}}</el-tag>
										</div>
									</div>
								</div>
							</div>
						</div>
					</LeftList>
				</div>
			</el-col>
			<el-col :span="18">
				<div class="rigth-box">
					<div class="rigth-box-content">
						<el-form ref="formRef" :model="objectForm" :rules="objectRules" label-width="140px">
							<el-form-item label="成员图标">
								<div class="active-box">
									<UploadPhotos :list="photoList" @update:list="updatePhotoList" :limit="1" />
								</div>
							</el-form-item>
							<el-form-item label="成员名称" prop="name">
								<el-input v-model="objectForm.name" class="input-w" placeholder="请填写成员名称" maxlength="50"
									show-word-limit></el-input>
							</el-form-item>
							<el-form-item label="成员号码" prop="cellphone">
								<el-input type="tel" maxlength="11" v-model="objectForm.cellphone" class="input-w"
									placeholder="请填写11位手机号码" @input="handlePhoneInput"></el-input>
							</el-form-item>
							<el-form-item label="成员邮箱" prop="email">
								<el-input type="text" v-model="objectForm.email" class="input-w"
									placeholder="请填写成员邮箱"></el-input>
							</el-form-item>
							<el-form-item label="成员职位" prop="position_rel">
								<el-select v-model="objectForm.position_rel" placeholder="请选择成员职位" class="input-w">
									<el-option v-for="item in posetion" :key="item.id" :label="item.title"
										:value="item.id">
									</el-option>
								</el-select>
								<span class="font_bule cursor_pointer under-line ml20" @click="positionClick">职位管理</span>
							</el-form-item>
							<el-form-item label="成员权限" prop="rights">
								<div class="font_bule cursor_pointer under-line">
									<span @click="rightsClick">权限设置</span>
								</div>
							</el-form-item>
							<el-form-item label="可见云店" prop="shopid_yd">
								<div class="select-wrapper flex_row">
									<el-select v-model="objectForm.shopid_yd" multiple filterable class="input-w"
										placeholder="请选择可见云店">
										<el-option v-for="item in yun_list" :key="item.id" :label="item.name"
											:value="item.id">
										</el-option>
									</el-select>
									<div v-if="objectForm.shopid_yd && objectForm.shopid_yd.length > 0"
										class="select-summary ml10">
										已选择 {{ objectForm.shopid_yd.length }} 个云店
									</div>
								</div>
							</el-form-item>
							<el-form-item label="归属门店" prop="shopid">
								<div class="select-wrapper flex_row">
									<el-select v-model="objectForm.shopid" multiple filterable class="input-w"
										placeholder="请选择归属门店">
										<el-option v-for="item in shop_list" :key="item.id" :label="item.name"
											:value="item.id">
										</el-option>
									</el-select>
									<div v-if="objectForm.shopid && objectForm.shopid.length > 0"
										class="select-summary ml10">
										已选择 {{ objectForm.shopid.length }} 个门店
									</div>
								</div>
							</el-form-item>
							<el-form-item label="归属仓库" prop="storeid">
								<div class="select-wrapper flex_row">
									<el-select v-model="objectForm.storeid" multiple filterable class="input-w"
										placeholder="请选择归属仓库">
										<el-option v-for="item in store_list" :key="item.id" :label="item.name"
											:value="item.id">
										</el-option>
									</el-select>
									<div v-if="objectForm.storeid && objectForm.storeid.length > 0"
										class="select-summary ml10">
										已选择 {{ objectForm.storeid.length }} 个仓库
									</div>
								</div>
							</el-form-item>
							<el-form-item label="置顶" prop="istop">
								<el-switch v-model="objectForm.istop" :active-value="'1'"
									:inactive-value="'2'"></el-switch>
							</el-form-item>
							<el-form-item label="启用" prop="status">
								<el-switch v-model="objectForm.status" :active-value="'1'"
									:inactive-value="'2'"></el-switch>
							</el-form-item>
						</el-form>
					</div>
					<div class="rigth-box-footer flex_between">
						<div class="summary-info"></div>
						<div class="action-buttons">
							<el-button type="primary" @click="sbumitHandle" size="large" class="btn-confirm"> 保 存
							</el-button>
						</div>
					</div>
				</div>
			</el-col>
		</el-row>
		<el-drawer :visible.sync="drawerRights" :modal="false" :size="'80%'" :title="'权限配置'">
			<rightsCard ref="rightsCardRef" :rights="objectForm.rights" @update:rights="updateRights"
				@rightsClose="rightsClose" />
		</el-drawer>
		<el-drawer :visible.sync="drawerPosition" :modal="false" :size="'80%'" :title="'职位管理'">
			<positionCard ref="positionCardRef" :position_rel="objectForm.position_rel" @update:position="updatePosition"
				@close="positionClose" />
		</el-drawer>
	</div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, nextTick } from '@vue/composition-api'
import LeftList from "@/pages/setting/components/leftList.vue"
import config from "@/js/conf/Config.js"
import staticConst from "@/js/const/StaticConst.js";
import tabBarConntrl from "@/js/TabBarContrl.js";

import API from "@/js/conf/api.js"
import { useCommonHooks } from '@/hooks/useCommonHooks.js'
import UploadPhotos from "@/components/commV2/UploadPhotos/index.vue"
import rightsCard from "@/pages/setting/components/rightsCard.vue"
import positionCard from "@/pages/setting/components/positionCard.vue"

// 使用全局状态
const { stateHooks } = useCommonHooks()

const maxPnum = 20
// 获取当前组件实例
const { proxy } = getCurrentInstance()

const templates = ref([{
	type: "slot",
	key: "name",
}, {
	type: "slot",
	key: "address",
},
])
const photoList = ref([])
// 表单数据
const query = ref({
	shopid: '',
	position: '',
	kw: '',
	ch: '',
	pfrom: 0,
	pnum: maxPnum,
})
const objectForm = ref({
	id: '',
	avatar: '',
	name: '',
	cellphone: '',
	email: '',
	rights: [],
	shopid_yd: '',
	shopid: '',
	storeid: '',
	position: {},
	position_rel: '',
	istop: '1',
	status: '1',
})
const detailID = ref('')
const posetion = ref([])

// 表单验证规则
const objectRules = ref({
	name: [
		{ required: true, message: '请输入成员名称', trigger: 'blur' }
	],
	cellphone: [
		{ required: true, message: '请输入成员号码', trigger: 'blur' },
		{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur' }
	],
	position_rel: [
		{ required: true, message: '请输入成员职位', trigger: 'blur' }
	],
	shopid_yd: [
		{ required: true, message: '请选择可见云店', trigger: 'blur' }
	],
	shopid: [
		{ required: true, message: '请选择归属门店', trigger: 'blur' }
	],
	storeid: [
		{ required: true, message: '请选择归属仓库', trigger: 'blur' }
	],
})

// 添加或修改 handlePhoneInput 方法
const handlePhoneInput = () => {
  objectForm.value.cellphone = objectForm.value.cellphone.replace(/[^0-9]/g, '');
  if (objectForm.value.cellphone.length > 11) {
    objectForm.value.cellphone = objectForm.value.cellphone.slice(0, 11);
  }
}

// 职位管理
const drawerPosition = ref(false)
const positionCardRef = ref(null)
const positionClick = async () => {
	drawerPosition.value = true
	await nextTick()
	setTimeout(() => {
		if (positionCardRef.value && typeof positionCardRef.value.open === 'function') {
			positionCardRef.value.open()
		}
	}, 100)
}
const positionClose = () => {
	drawerPosition.value = false
}
const updatePosition = (id) => {
	getLs()
	objectForm.value.position_rel = id
}

// 职位信息
const getLs = async () => {
    try {
        let res = await proxy.$api({
            url: config.company_position_ls, data: {}
        })
        let result = res.data || []
        if (res.status == 1) {
            posetion.value = result
        }
    } catch (error) {
        proxy.$message.error('获取职位列表失败')
    }
}

// 成员权限
const drawerRights = ref(false)
const rightsCardRef = ref(null)
const rightsClick = async () => {
	drawerRights.value = true
	// 使用nextTick确保抽屉和子组件完全渲染后再调用子组件方法
	await nextTick()
	// 添加额外的延迟确保子组件完全初始化
	setTimeout(() => {
		if (rightsCardRef.value && typeof rightsCardRef.value.open === 'function') {
			rightsCardRef.value.open()
		}
	}, 100)
}
const rightsClose = () => {
	drawerRights.value = false
}

// 处理权限更新的双向绑定
const updateRights = (newRights) => {
	objectForm.value.rights = newRights
}

const listData = ref([])
const selectedIndex = ref(0)
const lLoading = ref(false)
const lNoMore = ref(false)

const loadFun = () => {
	if (lNoMore.value || lLoading.value) return
	query.value.pfrom += 20
	if (listData.value && listData.value.length > 0) {
		getEventLs(false)
	}
}

const getEventLs = async (t = true) => {
	lLoading.value = true
	if (t == true) {
		query.value.pfrom = 0
		listData.value = []
	}
	let params = {
		...query.value
	}
	try {
		let res = await proxy.$api({ url: config.company_staff_ls, data: params })
		lLoading.value = false
		if (res.status == 1) {
			let result = res.data?.staff_ls
			if (result && result.length > 0) {
				listData.value.push(...result)
				// 确保索引在有效范围内
				const validIndex = Math.min(selectedIndex.value, listData.value.length - 1)
				if (t == true) {
					detailID.value = listData.value[validIndex]?.id
					getShopInfo()
				}
				if (res.status == 1 && result.length < maxPnum) {
					lNoMore.value = true
				} else {
					lNoMore.value = false
				}
			} else {
				lNoMore.value = true;
			}
		} else {
			lNoMore.value = true
		}
	} catch (error) {
		lLoading.value = false
		lNoMore.value = true
	} finally {
		lLoading.value = false
	}
}

// 成员信息
const getShopInfo = async () => {
	try {
		let res = await proxy.$api({
			url: config.company_staff_info, data: {
				id: detailID.value
			}
		})
		let result = res.data || {}
		if (res.status == 1) {
			objectForm.value = result;
			photoList.value = result.avatar ? [{ url: result.avatar }] : [];
			objectForm.value.position = result.position ? result.position : { id: '', name: '' }
		}
	} catch (error) {
		console.error('获取成员信息失败:', error)
	} finally {
	}
}

// 获取云店列表
const yun_list = ref([])
const getYdlistFun = async () => {
	let res = await proxy.$api({ url: config.YUN_SHOP_LS, data: { nt_all: 1 } });
	if (!res) return;
	if (res.status == 1 && res.data) {
		yun_list.value = res.data;
	}
}
getYdlistFun()

// 获取门店列表
const shop_list = ref([])
const getShopList = async function () {
	let res = await proxy.$api({ url: config.SHOP_LS, data: {} });
	if (res.status == 1 && res.data) {
		shop_list.value = res.data;
	}
}
getShopList()

const store_list = ref([])
const getStoreList = async () => {
	let res = await proxy.$api({ url: config.CK_STORE_STORE_CLS, data: {} });
	if (res.status == 1) {
		store_list.value = res.data?.ck;
	}
}
getStoreList()

const clickItem = (index) => {
	detailID.value = listData.value[index]?.id
	getShopInfo()
}

const addOrEdt = () => {
	resetFun()
	detailID.value = 0
	selectedIndex.value = null
}

const resetFun = () => {
	objectForm.value = {
		id: '',
		avatar: '',
		name: '',
		cellphone: '',
		email: '',
		rights: [],
		shopid_yd: '',
		shopid: '',
		storeid: '',
		position: {},
		position_rel: '',
		istop: '1',
		status: '1',
	}
	photoList.value = []
}

const updatePhotoList = (newList) => {
	photoList.value = newList
}

const sbumitHandle = async () => {
	try {
		// 表单验证
		const valid = await proxy.$refs.formRef.validate()
		if (!valid) {
			proxy.$message({
				message: '请完善表单信息',
				type: 'warning'
			})
			return
		}
		let params = {
			...objectForm.value,
			avatar: photoList.value.length > 0 ? photoList.value[0].name : '',
			position: objectForm.value.position_rel
		}
		console.log('params===', params)
		let res = await proxy.$api({ url: config.company_staff_save, data: params })
		if (res.status == 1) {
			proxy.$message({
				message: '保存成功，若是修改权限，需要重新登录才生效',
				type: 'success'
			})
			getEventLs()
			// proxy.$confirm('权限修改成功，需重新登录才生效，是否重新登录？', '提示', {
			// 	confirmButtonText: '确定',
			// 	cancelButtonText: '取消',
			// 	type: 'warning'
			// }).then(() => {
			// 	tabBarConntrl.close();
			// })
		} else {
			proxy.$message({
				message: res.msg || '保存失败',
				type: 'error'
			})
		}
	} catch (error) {
		console.error('保存失败:', error)
		proxy.$message({
			message: '请检查表单内容',
			type: 'error'
		})
	}
}

onMounted(async () => {
	getEventLs()
	getLs()
})

</script>

<style lang="scss" scoped>
div {
	box-sizing: border-box;
}

.limited {
	max-height: 100vh;
	height: calc(100vh - 90px);
	/* 确保最小高度为视窗高度 */
	overflow: hidden;

	::v-deep .el-row {
		height: 100%;
	}

	::v-deep .el-col {
		height: 100%;
	}

	.left-box,
	.rigth-box {
		width: 100%;
		padding: 0 10px 0 10px;
		height: 100%;

		.iconBox {
			font-size: 26px;
			cursor: pointer;
			position: relative;
			top: -6px;

			.search-icon {
				font-size: 20px;
				color: #333;
			}
		}
	}

	.left-box {
		border-right: 1px solid #e6e6e6;

		.store-header {
			box-sizing: border-box;
			border: 1px solid #f1f1f1;
			border-radius: 4px;
			box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
			padding: 0 14px;
			height: 60px;
		}

		.img-box {
			width: 50px;
			height: 50px;
			border-radius: 50%;
			margin-right: 10px;

			.img {
				width: 100%;
				height: 100%;
				border-radius: 50%;
				object-fit: cover;
			}
		}
	}

	.rigth-box {
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		height: 100%;
		/* 确保容器有明确高度 */
		overflow: hidden;

		.rigth-box-content {
			box-sizing: border-box;
			flex: 1;
			height: 0;
			/* 关键：让flex-grow生效 */
			min-height: 0;
			/* 允许收缩 */
			padding-right: 100px;
			overflow-y: auto;
			/* 内容溢出时显示滚动条 */
		}

		.rigth-box-footer {
			flex-shrink: 0;
			/* 防止footer被压缩 */
			border-top: 1px solid #f1f1f1;
			margin-top: 10px;
			padding: 14px 10px 4px;

			.summary-info {
				display: flex;
				align-items: center;
				gap: 16px;
			}

			.action-buttons {
				display: flex;
				gap: 12px;

				.btn-cancel {
					border-color: #cbd5e1;
					color: #64748b;
				}

				.btn-confirm {
					background-color: #3b82f6;
					border-color: #3b82f6;
				}
			}
		}
	}
}

.input-w {
	width: 400px;
}

// 为多选下拉框添加省略号样式
::v-deep .el-select__tags {
	max-width: calc(100% - 32px);
	overflow: hidden;
}

::v-deep .el-select__tags-text {
	max-width: 180px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	display: inline-block;
}

// Element UI 2.x 中 collapse-tags 的自定义控制
.custom-select {
	::v-deep .el-select__tags {

		// 限制显示的标签数量，隐藏第4个及以后的标签
		.el-tag:nth-child(n+4) {
			display: none;
		}
	}
}

// 多选显示区域样式
.select-wrapper {
	position: relative;

	.select-summary {
		margin-top: 4px;
		font-size: 12px;
		color: #909399;
		padding-left: 4px;
	}
}
</style>
